<template>
  
    <Row >
    
      <!-- 讨论详情版块 -->  
      <!-- 讨论的内容部分 -->
      <Panel   shadow :padding="10">
        <!-- 标题和它的标签：类型、是否置顶、是否关闭 -->
        <!-- <div style="justify-items: flex-start;">     -->
          <div style="margin-left: 24px; margin-top: -30px; display: inline-block; font-size: 25px;">{{discussion.discussion_title}}
            <Button type="ghost"
                size="small" shape="circle">{{this.displayType[discussion.discussion_type]}}
            </Button>

            <Button v-if="discussion.is_top" 
                style="background-color:#bb4a; color:#fff" size="small" shape="circle">{{$t('m.Is_Top')}}</Button>

            <Button v-if="discussion.closed" 
                style="background-color:#f066; color:#fff" size="small" shape="circle">{{$t('m.Is_Closed')}}</Button>
          </div>
          <el-button  v-if="discussion.problem"
            size="medium" 
            style="display: inline-block; position: absolute; right: 20px; " 
            type="primary" 
            round 
            plain 
            @click="goProblem"
          > 原题链接 </el-button>
        <!-- </div> -->
        <el-divider></el-divider>
        <el-row >
          <!-- 赞 和 收藏 -->
          <el-col style="width:4%;font-size: 30px;flex-direction:column;display: flex; align-items: center;" >
            
            <i v-if="t<2" @click="editLike(1)" class="el-icon-caret-top" style="font-size: 35px;"></i>
            <i v-if="t===2" @click="editLike(1)" class="el-icon-caret-top" style="color: orange;font-size: 35px;"></i>
            <div style="text-align: center;">{{discussion.like_number}}</div>
            <i v-if="t%2===0" @click="editLike(2)" class="el-icon-caret-bottom" style="font-size: 35px;"></i>
            <i v-if="t===1" @click="editLike(2)" class="el-icon-caret-bottom" style="color: orange;font-size: 35px;"></i>
            <i v-if="!star" @click="changeStar" class="el-icon-star-off"></i>
            <i v-if="star" @click="changeStar" class="el-icon-star-on" style="color:gold" ></i>
            <div v-if="discussion.star_number >0">{{discussion.star_number }}</div>
            
          </el-col >
          <el-col  style="width:96%;">
            <v-md-preview :text="discussion.discussion_text" @copy-code-success="handleCopyCodeSuccess"></v-md-preview>
              
            <!-- 额外信息 -->
            <div style="margin-top: 10px;">
              <ul class="detail">
                <!-- 浏览数 -->
                <li>
                  <i class="el-icon-view"></i> 
                  {{discussion.view_number }}
                </li>
                <!-- 回复数 -->
                <li>
                  <i class="el-icon-chat-line-square"></i> 
                  {{discussion.reply_number }}
                </li>
                  <!-- 右对齐的部分，主要是用户信息 -->
                <li style="float: right">
                  <!-- 如果是用户自己的讨论，他可以编辑 -->
                  <a v-if="discussion.created_by.id === user.id"
                    @click="editDiscussion()">
                    <i class="el-icon-edit"></i> 
                    {{$t('m.Edit')}}
                  </a> &nbsp;&nbsp;&nbsp;
                  <!-- 最后编辑时间 -->
                  <a @click="goUser(discussion.created_by.username)">{{discussion.created_by.username}}</a>
                  编辑于
                  {{discussion.last_edit_time | localtime('YYYY-M-D HH:mm') }}
                  <!-- 编辑者，todo: 跳转到编辑者的个人界面，可以显示用户的所有讨论和回复 -->
                </li>
              </ul>
            </div>
          </el-col >
        </el-row>
      </Panel>

      
      <Panel style="margin-top: 30px; padding: 20px" >
        <div slot="title">评论</div>
        <div style="padding: 0 30px " >
          <el-input
            type="textarea"
            placeholder="请输入评论,支持Latex 和 markdown 语法"
            v-model="discussionReply.reply_text"
            maxlength="2000"
            maxline="20"
            :autosize="{ minRows: 4, maxRows: 35 }"
            show-word-limit        
          >
          </el-input>
          <div style="text-align: right; ">
            <el-button type="text" style="font-size:18px" @click="finishCreateDiscussionReply" >提交评论</el-button>
          </div>
        </div>

        <el-divider></el-divider>
        
        <p v-if="discussion.reply_number === 0" id="no-reply">{{$t('m.No_Reply')}}</p>
        <reply-tree-node :replies="replies" :open="true" :closed="discussion.closed"
                        :open_next="open_next" :init="init"
                        :goUser="goUser"></reply-tree-node>
        <Pagination :total="total" :pageSize="limit" @on-change="getReply" :current.sync="page"></Pagination>
      </Panel>
      <!-- 是否删除讨论 -->
      <el-dialog title="确认删除" :visible.sync="deleting">
        {{$t('m.Are_you_sure_you_want_to_delete_this_discussion')}}
        <!-- 底部，取消或确定 -->
        <span slot="footer" class="dialog-footer">
          <el-button plain type="primary" @click.native="cancelDeleteDiscussion">{{$t('m.Cancel')}}</el-button>
          <el-button type="primary" @click.native="finishDeleteDiscussion">{{$t('m.Sure')}}</el-button>
        </span>
      </el-dialog>
      
      <Tooltip v-if="canDelete" :style="{'bottom': '200px', 'right': '55px'}"
          class="ivu-back-top ivu-back-top-show" placement="top" content="删除">
          <div class="ivu-back-top ivu-back-top-show" 
              style="bottom: 160px; right: 30px;">
              <Icon type="trash-a" class="top" 
              @click.native="deleteDiscussion"></Icon>
          </div>
      </Tooltip>

    </Row>
  
</template>

<script>
  import api from '@oj/api'
  import { mapGetters } from 'vuex'
  import utils from '@/utils/utils'
  import { USER_TYPE } from '@/utils/constants'
  import Pagination from '@/pages/oj/components/Pagination'
  import Simditor from '@admin/components/Simditor.vue'
  import ReplyTreeNode from '@/pages/oj/components/ReplyTreeNode'
  import time from '@/utils/time'
  const limit = 10
  export default {
    name: 'discussion-details',
    components: {
      Pagination,
      Simditor,
      ReplyTreeNode
    },
    data () {
      return {
        page: 1,
        query: {
          discussionID: ''
        },
        limit: limit,
        total: 0,
        rows: '',
        title: this.$i18n.t('m.All_Discussion'),
        discussion: {
          created_by: {
            id: null
          }
        },
        discussionID: '',
        replies: [],
        open_next: [],
        reply_text: '',
        creatingID: 0,
        deleting: false,
        currentDiscussion: {},
        discussionReply: {},
        discussion_type: '',
        currentReply: {},
        star: false,
        t: 0,
        nt: 0,
        like_id: 0,
        displayType: {'Solution': '题解', 'Share': '分享', 'Integrated': '问答'}
      }
    },
    beforeRouteEnter (to, from, next) {
      let query = {}
      query.discussion_id = to.params.discussionID
      api.getReplyList(0, limit, query).then((res) => {
        next((vm) => {
          vm.replies = res.data.data.results
          vm.total = res.data.data.total
          vm.open_next = res.data.data.open_next
        })
      }, (res) => {
        next()
      })
    },
    mounted () {
      this.init()
      this.addViewCount()
    },
    methods: {
      addViewCount () {
        api.addViewCount(this.discussionID).then(res => {
          // 不知道为啥时灵时不灵。。
          this.discussion.view_number += 1
        })
      },
      init () {
        let route = this.$route.query
        this.query.discussion_id = this.$route.params.discussionID
        this.page = parseInt(route.page) || 1
        this.getDiscussion()
        this.getReply()
        if (this.user.id) {
          this.getStarStatus()
          this.getLike()
        }
        console.log('USER', this.user)
      },
      getReply (page = 1) {
        let offset = (page - 1) * this.limit
        api.getReplyList(offset, this.limit, this.query).then((res) => {
          this.replies = res.data.data.results
          this.total = res.data.data.total
          this.open_next = res.data.data.open_next
        })
      },
      getStarStatus () {
        let query = {}
        query.type = 'discussion'
        query.id = this.discussionID
        api.starExists(query).then(res => {
          // console.log(res)
          this.star = res.data.data
        })
      },
      getLike () {
        api.getLike({id: this.discussionID}).then(res => {
          console.log(res.data.data)
          if (res.data.data !== -1) {
            this.t = res.data.data.num
            console.log(this.t)
            this.like_id = res.data.data.id
          } else {
            api.createLike({discussion_id: this.discussionID, num: 0}).then(res => {
              this.t = 0
              this.like_id = res.data.data.id
            })
          }
        })
      },
      editLike (w) {
        if (w === 1) {
          if (this.t === 1) {
            this.nt = 2
          } else {
            this.nt = this.t ^ 2
          }
        } else {
          if (this.t === 2) {
            this.nt = 1
          } else {
            this.nt = this.t ^ 1
          }
        }
        let like = {}
        like.id = this.like_id
        like.num = this.nt
        like.change = -(this.nt === 1) + (this.nt === 2) + (this.t === 1) - (this.t === 2)
        console.log('ccccc', like.change)
        api.editLike(like).then(res => {
          this.t = res.data.data.num
          this.discussion.like_number += like.change
        })
      },
      changeStar () {
        if (!this.star) {
          let par = {}
          par.discussion_id = this.discussionID
          api.createStar(par).then(res => {
            this.star = !this.star
          })
        } else {
          let par = {}
          par.star_id = this.discussionID
          par.type = 'discussion'
          api.deleteStar(par).then(res => {
            this.star = !this.star
          })
        }
      },
      goBack () {
        let query = {}
        if (this.discussion.problem) {
          query.problem_id = this.discussion.problem._id
        }
        this.$router.push({name: 'discussion-list', query})
      },
      getDiscussion () {
        this.discussionID = this.$route.params.discussionID
        this.discussionReply.reply_to = this.discussionID
        this.discussionReply.reply_to_discussion = true
        api.getDiscussion(this.discussionID).then(res => {
          this.discussion = res.data.data
        })
      },
      changeRoute () {
        let query = Object.assign({}, this.query)
        query.page = this.page
        this.$router.push({
          name: 'discussion-list',
          query: utils.filterEmptyValue(query)
        })
      },
      editDiscussion () {
        if (this.discussion.problem) {
          this.$router.push({name: 'discussion-edit', params: {discussionID: this.discussion.id, problem_id: this.discussion.problem._id}})
        } else {
          this.$router.push({name: 'discussion-edit', params: {discussionID: this.discussion.id}})
        }
      },
      deleteDiscussion () {
        this.deleting = true
      },
      cancelDeleteDiscussion () {
        this.deleting = false
      },
      finishDeleteDiscussion () {
        this.deleting = false
        api['deleteDiscussion']({discussion_id: this.discussionID}).then(res => {
          this.$success('删除成功！')
          this.goBack()
        })
      },
      finishCreateDiscussionReply () {
        if (!this.discussionReply.reply_text) { return }
        api['createReply'](this.discussionReply).then(res => {
          this.init()
          this.discussionReply.reply_text = ''
        }).catch()
      },
      onOrderChange (order) {
        this.query.order_by = order
        this.page = 1
        this.changeRoute()
      },
      onProblemChange (problemId) {
        this.query.problem_id = problemId
        this.page = 1
        this.changeRoute()
      },
      goProblem () {
        const {href} = this.$router.resolve({
          name: 'problem-details',
          params: {problemID: this.discussion.problem._id}
        })
        window.open(href, '_blank')
        // this.$router.push({name: 'problem-details', params: {problemID: this.discussion.problem._id}})
      },
      goUser (username) {
        // const {href} = this.$router.resolve({
        //   name: 'user-home-discussion',
        //   query: {username: username}
        // })
        // window.open(href, '_blank')
        // this.$router.push({
        //   name: 'user-home-discussion',
        //   query: {username: username}
        // })
      },
      getDuration (startTime, endTime) {
        return time.duration(startTime, endTime)
      },
      handleCopyCodeSuccess () {
        this.$notify({
          title: '复制成功',
          type: 'success',
          duration: 2000
        })
      }
    },
    computed: {
      ...mapGetters(['user', 'theme']),
      isAdmin () {
        return this.user.admin_type === USER_TYPE.SUPER_ADMIN
      },
      canDelete () {
        return this.discussion.created_by.id === this.user.id || this.isAdmin
      }
    },
    watch: {
      '$route' (newVal, oldVal) {
        if (newVal !== oldVal) {
          this.init()
        }
      }
    }
  }
</script>

<style scoped>
  .detail > li{
    margin-left: 20px;
    display: inline-block;
    font-size: 16px;
  }
  .content-container {
    padding: 0 20px 20px 20px;
  }
  .top {
    padding: 10px;
    width: 45px;
    background: rgba(0, 0, 0, .5);
    color: #fff;
    text-align: center;
    border-radius: 2px;
  }
  #no-reply {
    text-align: center;
  font-size: 16px;
    padding: 20px;
  }
</style>